<template>
  <div class="room-manage">
    <el-card>
      <div class="card-header">
        <h2>机房管理</h2>
        <el-button type="primary" @click="showAddRoomDialog = true"
          >添加机房</el-button
        >
      </div>

      <el-table :data="rooms" border v-loading="loading" max-width="100%" fit>
        <el-table-column prop="id_" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="机房名称"></el-table-column>
        <el-table-column prop="location" label="位置"></el-table-column>
        <el-table-column
          prop="total_computers"
          label="总机器数"
        ></el-table-column>
        <el-table-column
          prop="available_computers"
          label="可用机器数"
        ></el-table-column>
        <el-table-column
          prop="hourly_rate"
          label="每小时费率"
          :formatter="formatCurrency"
        ></el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'active'" type="success"
              >正常</el-tag
            >
            <el-tag v-if="scope.row.status === 'closed'" type="info"
              >停用</el-tag
            >
            <el-tag
              v-else-if="scope.row.status === 'maintenance'"
              type="warning"
              >维护</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column width="200" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditRate(scope.row)"
              >修改费率</el-button
            >
            <el-button
              size="small"
              @click="handleModifyRoomStatus(scope.row)"
              >修改状态</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加机房对话框 -->
    <el-dialog
      title="添加机房"
      v-model="showAddRoomDialog"
      @close="resetRoomForm"
    >
      <el-form :model="newRoom" :rules="roomRules" ref="roomFormRef">
        <el-form-item label="机房名称" prop="name">
          <el-input
            v-model="newRoom.name"
            placeholder="请输入机房名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input
            v-model="newRoom.location"
            placeholder="请输入机房位置"
          ></el-input>
        </el-form-item>
        <el-form-item label="总机器数" prop="total_computers">
          <el-input-number
            v-model="newRoom.total_computers"
            :min="1"
            :step="1"
            style="width: 100%"
            placeholder="请输入总机器数"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="每小时费率" prop="hourly_rate">
          <el-input-number
            v-model="newRoom.hourly_rate"
            :min="0.01"
            :step="0.5"
            :precision="2"
            style="width: 100%"
            placeholder="请输入每小时费率"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddRoomDialog = false">取消</el-button>
        <el-button type="primary" @click="addRoom" :loading="adding"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 修改费率对话框 -->
    <el-dialog
      title="修改费率"
      v-model="showEditRateDialog"
      @close="resetRateForm"
    >
      <el-form :model="editRateForm" :rules="rateRules" ref="rateFormRef">
        <el-form-item label="机房名称">
          <el-input v-model="editRateForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前费率">
          <el-input v-model="editRateForm.current_rate" disabled>
            <template #append>元/小时</template>
          </el-input>
        </el-form-item>
        <el-form-item label="新费率" prop="hourly_rate">
          <el-input-number
            v-model="editRateForm.hourly_rate"
            :min="0.01"
            :step="0.5"
            :precision="2"
            style="width: 100%"
            placeholder="请输入新费率"
          >
            <template #append>元/小时</template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditRateDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmEditRate" :loading="updating"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog
      title="修改状态"
      v-model="showModifyRoomStatusDialog"
      @close="resetRoomStatusForm"
    >
      <el-form :model="roomStatusForm" ref="roomStatusFormRef">
        <el-form-item label="机房名称">
          <el-input v-model="roomStatusForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="roomStatusForm.status" placeholder="请选择新状态">
            <el-option label="正常" value="active"></el-option>
            <el-option label="停用" value="closed"></el-option>
            <el-option label="维护" value="maintenance"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showModifyRoomStatusDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmModifyRoomStatus"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  getComputerRooms,
  createComputerRoom,
  updateRoomRate,
  updateRoomStatus,
} from "../api/rooms";
import { ElMessage, ElMessageBox } from "element-plus";

// 响应式数据
const rooms = ref([]);
const loading = ref(false);
const adding = ref(false);
const updating = ref(false);

const showAddRoomDialog = ref(false);
const showEditRateDialog = ref(false);
const showModifyRoomStatusDialog = ref(false);

const newRoom = ref({
  name: "",
  location: "",
  total_computers: 1,
  hourly_rate: 5.0,
});

const editRateForm = ref({
  room_id: null,
  name: "",
  current_rate: 0,
  hourly_rate: 0,
});

const roomStatusForm = ref({
  room_id: null,
  name: "",
  status: "",
});

// 表单引用
const roomFormRef = ref(null);
const rateFormRef = ref(null);
const roomStatusFormRef = ref(null);

// 验证规则
const roomRules = ref({
  name: [
    { required: true, message: "请输入机房名称", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "机房名称长度在 2 到 20 个字符",
      trigger: "blur",
    },
  ],
  location: [
    { required: true, message: "请输入机房位置", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "位置描述长度在 2 到 50 个字符",
      trigger: "blur",
    },
  ],
  total_computers: [
    { required: true, message: "请输入总机器数", trigger: "blur" },
    { type: "number", min: 1, message: "总机器数必须大于0", trigger: "blur" },
  ],
  hourly_rate: [
    { required: true, message: "请输入每小时费率", trigger: "blur" },
    { type: "number", min: 0.01, message: "费率必须大于0", trigger: "blur" },
  ],
});

const rateRules = ref({
  hourly_rate: [
    { required: true, message: "请输入新费率", trigger: "blur" },
    { type: "number", min: 0.01, message: "费率必须大于0", trigger: "blur" },
  ],
});

// 格式化金额
const formatCurrency = (row, column, cellValue) => {
  return "¥" + parseFloat(cellValue).toFixed(2);
};

// 获取机房列表
const fetchRooms = async () => {
  loading.value = true;
  try {
    const response = await getComputerRooms();
    rooms.value = response.data;
    console.log("机房数据:", rooms.value);
  } catch (error) {
    ElMessage.error(
      "获取机房列表失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取机房列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 重置机房表单
const resetRoomForm = () => {
  newRoom.value = {
    name: "",
    location: "",
    total_computers: 1,
    hourly_rate: 5.0,
  };
  roomFormRef.value?.clearValidate();
};

const resetRoomStatusForm = () => {
  roomStatusForm.value = {
    room_id: null,
    name: "",
    status: "",
  };
  roomStatusFormRef.value?.clearValidate();
};

// 重置费率表单
const resetRateForm = () => {
  editRateForm.value = {
    room_id: null,
    name: "",
    current_rate: 0,
    hourly_rate: 0,
  };
  rateFormRef.value?.clearValidate();
};

// 添加机房
const addRoom = async () => {
  if (!roomFormRef.value) return;

  try {
    await roomFormRef.value.validate();
    adding.value = true;

    await createComputerRoom(newRoom.value);
    ElMessage.success("添加机房成功");
    showAddRoomDialog.value = false;
    await fetchRooms();
  } catch (error) {
    if (error.errors) {
      return;
    }
    ElMessage.error(
      "添加机房失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("添加机房失败:", error);
  } finally {
    adding.value = false;
  }
};

// 处理修改费率
const handleEditRate = (room) => {
  editRateForm.value.room_id = room.id_;
  editRateForm.value.name = room.name;
  editRateForm.value.current_rate = room.hourly_rate;
  editRateForm.value.hourly_rate = room.hourly_rate;
  showEditRateDialog.value = true;
};

const handleModifyRoomStatus = (room) => {
  roomStatusForm.value = {
    room_id: room.id_,
    name: room.name,
    status: room.status,
  };
  showModifyRoomStatusDialog.value = true;
};

const confirmModifyRoomStatus = async () => {
  if (!roomStatusForm.value) return;
  try {
    await roomStatusFormRef.value.validate();
    await ElMessageBox.confirm(
      `确定要将机房 "${roomStatusForm.value.name}" 的状态修改为 "${roomStatusForm.value.status}" 吗？`,
      "确认修改状态",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    updating.value = true;

    await updateRoomStatus(
      roomStatusForm.value.room_id,
      roomStatusForm.value.status
    );
    ElMessage.success(`修改状态为 ${roomStatusForm.value.status} 成功`);
    await fetchRooms();
  } catch (error) {
    console.error("修改状态失败:", error);
  } finally {
    updating.value = false;
    showModifyRoomStatusDialog.value = false;
  }
};
// 确认修改费率
const confirmEditRate = async () => {
  if (!rateFormRef.value) return;

  try {
    await rateFormRef.value.validate();

    await ElMessageBox.confirm(
      `确定要将机房 "${
        editRateForm.value.name
      }" 的费率从 ¥${editRateForm.value.current_rate.toFixed(
        2
      )}/小时 修改为 ¥${editRateForm.value.hourly_rate.toFixed(2)}/小时 吗？`,
      "确认修改费率",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    updating.value = true;

    console.log("发送费率更新请求:", {
      room_id: editRateForm.value.room_id,
      hourly_rate: editRateForm.value.hourly_rate,
    });

    // 尝试使用通用更新接口而不是特定的rate接口
    const updateData = parseFloat(editRateForm.value.hourly_rate);

    await updateRoomRate(editRateForm.value.room_id, updateData);

    ElMessage.success("费率修改成功");
    showEditRateDialog.value = false;
    await fetchRooms();
  } catch (error) {
    if (error === "cancel") {
      return;
    }

    // 详细错误信息
    console.error("费率修改失败详情:", {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message,
      config: error.config,
    });

    let errorMessage = "费率修改失败";
    if (error.response?.data?.detail) {
      if (Array.isArray(error.response.data.detail)) {
        errorMessage +=
          ": " + error.response.data.detail.map((d) => d.msg).join(", ");
      } else {
        errorMessage += ": " + error.response.data.detail;
      }
    }

    ElMessage.error(errorMessage);
  } finally {
    updating.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchRooms();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.room-manage {
  padding: 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
